package com.youlai.boot.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.youlai.boot.core.security.model.SysUserDetails;
import com.youlai.boot.shared.websocket.model.ChatMessage;
import com.youlai.boot.shared.websocket.service.OnlineUserService;
import com.youlai.boot.system.enums.YesNoEnum;
import com.youlai.boot.system.model.entity.LpsOrder;
import com.youlai.boot.system.model.vo.LpsOrderNODownloadVO;
import com.youlai.boot.system.service.LpsOrderService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.mapper.LpsOrderDownloadMapper;
import com.youlai.boot.system.service.LpsOrderDownloadService;
import com.youlai.boot.system.model.entity.LpsOrderDownload;
import com.youlai.boot.system.model.form.LpsOrderDownloadForm;
import com.youlai.boot.system.model.query.LpsOrderDownloadQuery;
import com.youlai.boot.system.model.vo.LpsOrderDownloadVO;
import com.youlai.boot.system.converter.LpsOrderDownloadConverter;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 下载记录服务实现类
 *
 * @author youlaitech
 * @since 2025-08-10 19:52
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LpsOrderDownloadServiceImpl extends ServiceImpl<LpsOrderDownloadMapper, LpsOrderDownload> implements LpsOrderDownloadService {

    private final LpsOrderDownloadConverter lpsOrderDownloadConverter;
    @Resource
    @Lazy
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    @Lazy
    private LpsOrderService lpsOrderService;
    // 修改这行代码
    private final static String DESTINATION = "/queue/greeting";
    private final static String SENDER = "root";

    /**
    * 获取下载记录分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<LpsOrderDownloadVO>} 下载记录分页列表
    */
    @Override
    public IPage<LpsOrderDownloadVO> getLpsOrderDownloadPage(LpsOrderDownloadQuery queryParams) {
        Page<LpsOrderDownloadVO> pageVO = this.baseMapper.getLpsOrderDownloadPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取下载记录表单数据
     *
     * @param id 下载记录ID
     * @return
     */
    @Override
    public LpsOrderDownloadForm getLpsOrderDownloadFormData(Long id) {
        LpsOrderDownload entity = this.getById(id);
        return lpsOrderDownloadConverter.toForm(entity);
    }
    
    /**
     * 新增下载记录
     *
     * @param formData 下载记录表单对象
     * @return
     */
    @Override
    public boolean saveLpsOrderDownload(LpsOrderDownloadForm formData) {
        LpsOrderDownload entity = lpsOrderDownloadConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新下载记录
     *
     * @param id   下载记录ID
     * @param formData 下载记录表单对象
     * @return
     */
    @Override
    public boolean updateLpsOrderDownload(Long id,LpsOrderDownloadForm formData) {
        LpsOrderDownload entity = lpsOrderDownloadConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除下载记录
     *
     * @param ids 下载记录ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteLpsOrderDownloads(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的下载记录数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }


    @Override
    public void handleLpsOrderDownload(SysUserDetails userDetails, LpsOrder lpsOrder) {
        LpsOrderDownload orderDownload = baseMapper.getLpsOrderDownload(lpsOrder.getId(), userDetails.getUserId());
        if (Objects.isNull(orderDownload)){
            orderDownload = new LpsOrderDownload();
            orderDownload.setId(IdUtil.getSnowflakeNextId());
            orderDownload.setRemindTime(LocalDateTime.now());
            orderDownload.setCreateTime(LocalDateTime.now());
        }
        orderDownload.setOrderId(lpsOrder.getId());
        orderDownload.setUserId(userDetails.getUserId());
        orderDownload.setDeptId(userDetails.getDeptId());
        orderDownload.setFileName(lpsOrder.getFileName());
        orderDownload.setIsDownload(YesNoEnum.YES.getType());
        orderDownload.setUpdateTime(LocalDateTime.now());
        orderDownload.setDownloadTime(LocalDateTime.now());

        this.saveOrUpdate(orderDownload);

        String username = userDetails.getUsername();
        // 延迟发送消息，确保连接完全建立
        CompletableFuture.runAsync(() -> {
            try {
                // 等待连接完全建立
                Thread.sleep(500);

                // 查询当前连接用户的未下载数量
                LpsOrderNODownloadVO noDownloadUser = lpsOrderService.getNoDownloadUser(username);
                if (Objects.isNull(noDownloadUser)){
                    noDownloadUser = new LpsOrderNODownloadVO();
                    noDownloadUser.setNum(0L);
                }
                messagingTemplate.convertAndSendToUser(username, DESTINATION,new ChatMessage(SENDER, String.valueOf(noDownloadUser.getNum())));
                log.info("订单下载 WebSocket发送订单提醒消息发送完成: 用户={}", username);
            } catch (Exception e) {
                log.error("订单下载 WebSocket发送订单提醒消息失败: 用户={}", username, e);
            }
        });

    }


    /**
     * @param orderIds
     */
    @Override
    public void deleteByOrderIds(List<Long> orderIds) {
        this.baseMapper.deleteByOrderIds(orderIds);
    }
}
